package com.auxgroup.smarthome.service;

import com.alibaba.fastjson.JSON;
import com.auxgroup.smarthome.BeanUtils;
import com.auxgroup.smarthome.consant.UpmsRedisKeyManage;
import com.auxgroup.smarthome.dq.Criteria;
import com.auxgroup.smarthome.dq.Restrictions;
import com.auxgroup.smarthome.dto.LoginDto;
import com.auxgroup.smarthome.dto.SearchUserDto;
import com.auxgroup.smarthome.dto.UpdatePersonCenterDto;
import com.auxgroup.smarthome.dto.UpdateUserDto;
import com.auxgroup.smarthome.dto.UserDto;
import com.auxgroup.smarthome.dto.UserSearchDto;
import com.auxgroup.smarthome.entity.LoginStatus;
import com.auxgroup.smarthome.entity.MenuEntity;
import com.auxgroup.smarthome.entity.RoleEntity;
import com.auxgroup.smarthome.entity.RoleTag;
import com.auxgroup.smarthome.entity.UserEntity;
import com.auxgroup.smarthome.entity.UserStatus;
import com.auxgroup.smarthome.entity.UserTypeEnmu;
import com.auxgroup.smarthome.filter.PermissionSecurityUserService;
import com.auxgroup.smarthome.jwt.JwtConstant;
import com.auxgroup.smarthome.jwt.JwtUtils;
import com.auxgroup.smarthome.mail.GmailSender;
import com.auxgroup.smarthome.redis.config.ObjectRedis;
import com.auxgroup.smarthome.repo.MenuRepo;
import com.auxgroup.smarthome.repo.RoleRepo;
import com.auxgroup.smarthome.repo.UserRepo;
import com.auxgroup.smarthome.session.SessionMenu;
import com.auxgroup.smarthome.session.SessionUser;
import com.auxgroup.smarthome.syscode.Syscode;
import com.auxgroup.smarthome.utils.NewDateUtils;
import com.auxgroup.smarthome.utils.common.LOG;
import com.auxgroup.smarthome.vo.AccessTokenVo;
import com.auxgroup.smarthome.vo.LoginVo;
import com.auxgroup.smarthome.vo.RefreshTokenVo;
import com.auxgroup.smarthome.vo.UserListVo;
import com.auxgroup.smarthome.web.ApiResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.persistence.criteria.Predicate;
import java.lang.reflect.Field;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Created by kevinchen on 2016/12/20.
 */
@Service
public class UserService  {

    @Autowired
    private UserRepo userRepo;
    @Autowired
    private RoleRepo roleRepo;
    @Autowired
    private MenuRepo menuRepo;
    @Autowired
    private PermissionSecurityUserService permissionSecurityUserService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private ObjectRedis objectRedis;
    @Autowired
    private GmailSender gmailSender;


    public boolean isExistUserName(String userName){
        return userRepo.findByUserName(userName) != null ? true : false;
    }

    public boolean isExistUserName( String uid,String userName){
        UserEntity userEntity = userRepo.findByUserName(userName);
        return userEntity != null && userEntity.getId().compareTo(uid)!= 0 ? true : false;
    }

    public ApiResponse isExistUsername(String username){
        boolean isExist = isExistUserName(username);
        if (isExist){
            return ApiResponse.prompt(Syscode.ACCOUNT_EXISTS);
        }
        return ApiResponse.prompt(Syscode.ACCOUNT_NOT_EXISTS);
    }

    public UserEntity getUserById(String id){
        return userRepo.findOne(id);
    }


    @Transactional
    public ApiResponse deleteUserById(String id){
        String uid = permissionSecurityUserService.getSubjectFromAccessToken();
        UserEntity currUserEntity =  userRepo.findOne(uid);
        if (!currUserEntity.getRole().getRoleTag().equals(RoleTag.SUPPERROLE)) {
            return ApiResponse.prompt(Syscode.NO_PERMISSION);
        }
        UserEntity userEntity = userRepo.findOne(id);
        if (userEntity == null ){
            return ApiResponse.prompt(Syscode.ACCOUNT_NOT_EXISTS);
        }
        // 后台人员
        if(userEntity.getUserType().equals(UserTypeEnmu.BACKSTAGE)) {
            if(userEntity.getRole().getRoleTag().equals(RoleTag.SUPPERROLE)) {
                return ApiResponse.prompt(Syscode.SUPPERROLE_ACOUNT_NOT_PERMISS_DEL);
            }
        }
        /**
         * modify by lixiaoxiao 2017/9/9 修改未删除用户的bug
         */
        userRepo.delete(id);
        return ApiResponse.prompt(Syscode.SC_OK);
    }

    public ApiResponse deleteUserByIds(String ids) {
        String[] idStrs = ids.split(",");
        for(String id: idStrs) {
            ApiResponse apiResponse = deleteUserById(id);
            if(!apiResponse.isNotErrorCode()) {
                return apiResponse;
            }
        }
        return ApiResponse.prompt(Syscode.SC_OK);
    }

    public Page<UserListVo> findAll(Pageable pageable){
        Page<UserEntity> userEntities = userRepo.findAll(pageable);
        List<UserEntity> contents = userEntities.getContent();
        List<UserListVo> userListVos = new ArrayList<UserListVo>();
        for (Iterator<UserEntity> iterator = contents.iterator(); iterator.hasNext(); ) {
            UserEntity userEntity =  iterator.next();
            userListVos.add(new UserListVo(userEntity));
        }
        return new PageImpl(userListVos, pageable, userEntities.getTotalElements());
    }

    // 普通管理员连续失败5次需要输入验证码
    private static final int NEED_CAPTCHACODE = 5;
    // 超级管理员连续登录失败10次停用账号2个小时， 普通管理员连续失败10次后停用账号，需要超级管理员恢复
    private static final int DISABLE_ACCOUNT = 10;

    public ApiResponse<LoginVo> login(LoginDto loginDto){
        UserEntity userEntity =userRepo.findByUserName(loginDto.getUserName());
        if(null == userEntity) {
            return ApiResponse.prompt(Syscode.ACCOUNT_NOT_EXISTS);
        }
        // 登录失败次数
        int failCounter = userEntity.getLoginFailCounter() == null ? 0 : userEntity.getLoginFailCounter() ;
        // 普通用户出错超过5次需要输入验证码
        if(!RoleTag.SUPPERROLE.equals(userEntity.getRole().getRoleTag()) && failCounter >= NEED_CAPTCHACODE) {
            loginDto.setNeedIsCaptcha(true);
        }
        //验证码校验
        if (loginDto.isNeedIsCaptcha()){
            String captchaCode = loginDto.getCaptchaCode();
            if (captchaCode == null){
                return ApiResponse.prompt(Syscode.INVALID_CAPTCHA);
            }
            String redisKey = UpmsRedisKeyManage.CAPTCHA_REDIS_PREFIX + captchaCode;
            String captchaValue =  redisTemplate.opsForValue().get(redisKey);
            if (captchaValue == null) {
                return ApiResponse.prompt(Syscode.INVALID_CAPTCHA);
            }
            redisTemplate.delete(redisKey);
            if (captchaValue.compareTo(captchaCode) != 0) {
                return ApiResponse.prompt(Syscode.INVALID_CAPTCHA);
            }
        }

        if(failCounter >= DISABLE_ACCOUNT) {
            if(RoleTag.SUPPERROLE.equals(userEntity.getRole().getRoleTag())) {
                LocalDateTime forbitTime = LocalDateTime.ofInstant(Instant.ofEpochSecond(userEntity.getLoginFailTime()), NewDateUtils.getBeijingZoneId()).plusHours(2);
                LocalDateTime now = LocalDateTime.now(NewDateUtils.getBeijingZoneId());
                if(now.isBefore(forbitTime)) {
                    return ApiResponse.prompt(Syscode.ADMIN_LOGIN_FAIL_TEN_TIMES);
                } else {
                    userEntity.setLoginFailCounter(0);
                    userEntity.setUserStatus(UserStatus.NORMAL);
                    userRepo.save(userEntity);
                }
            } else {
                return ApiResponse.prompt(Syscode.LOGIN_FAIL_TEN_TIMES);
            }
        }
        if (!userEntity.isAuthentication(loginDto.getPassword())){
            userEntity.recordLoginFail();
            userRepo.save(userEntity);
            return ApiResponse.prompt(Syscode.ACCOUNT_PWD_ERROR);
        }
        if (UserStatus.DISABLED.equals(userEntity.getUserStatus())){
            return ApiResponse.prompt(Syscode.ACCOUNT_IS_FORBIDDEN);
        }
        try {
            long nowMillis = System.currentTimeMillis();
            String accessToken = JwtUtils.createJWT(JwtConstant.JWT_SECRET,nowMillis,JwtConstant.JWT_ID,userEntity.getId() , JwtConstant.JWT_TTL);
            AccessTokenVo accessTokenVo = new AccessTokenVo(accessToken,"bearer",JwtConstant.JWT_TTL);
            String refreshToken = JwtUtils.createJWT(JwtConstant.JWT_SECRET,nowMillis,JwtConstant.JWT_ID, userEntity.getId(), JwtConstant.JWT_REFRESH_TTL);
            RefreshTokenVo refreshTokenVo = new RefreshTokenVo(refreshToken,JwtConstant.JWT_REFRESH_TTL);
            SessionUser sessionUser = userEntity.createSessionUser();
            String userinfo = JSON.toJSONString(sessionUser);
            userEntity.setLoginFailCounter(0);
            userEntity.setLoginStatus(LoginStatus.ONLINE);
            userEntity.setLastLoginTime(NewDateUtils.getCurrentEpochSecond());
            redisTemplate.opsForValue().set(userEntity.getId(), userinfo, JwtConstant.JWT_REFRESH_TTL, TimeUnit.MILLISECONDS);
            userRepo.save(userEntity);
            return ApiResponse.ok(new LoginVo(accessTokenVo,refreshTokenVo));
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResponse.prompt(Syscode.JWT_TOKEN_INVALID);
        }
    }


    public ApiResponse logout(){
        String uid = permissionSecurityUserService.getSubjectFromAccessToken();
        redisTemplate.delete(uid);
        UserEntity userEntity = userRepo.findOne(uid);
        if (userEntity == null){
            return ApiResponse.ok(Syscode.ACCOUNT_NOT_EXISTS);
        }
        userEntity.setLoginStatus(LoginStatus.OFF);
        userRepo.save(userEntity);
        return ApiResponse.prompt(Syscode.SC_OK);
    }


    public ApiResponse createUser(UserDto userDto){
        if (StringUtils.isBlank(userDto.getRoleId())){
            return ApiResponse.prompt(Syscode.ROLE_NOT_NULL);
        }
        RoleEntity roleEntity = roleRepo.findOne(userDto.getRoleId());
        if (roleEntity==null){
            return ApiResponse.prompt(Syscode.ROLE_NOT_EXISTS);
        }
        if(!roleEntity.getRoleTag().equals(RoleTag.COMMONROLE)) {
            return ApiResponse.prompt(Syscode.GENERAL_ROLE_PERMIT);
        }
        if(isExistUserName(userDto.getUserName())){
            return ApiResponse.prompt(Syscode.USER_IS_EXISTS);
        }
        if (StringUtils.isBlank(userDto.getPassword())){
            return ApiResponse.prompt(Syscode.PASSWORD_NOT_NULL);
        }
        UserEntity newEntity = userDto.createUser(roleEntity);
        userRepo.save(newEntity);
        return ApiResponse.ok(newEntity.getId());
    }


    public ApiResponse updateUser(String uid, UpdateUserDto userDto){
        RoleEntity roleEntity = roleRepo.findOne(userDto.getRoleId());
        if (roleEntity==null){
            return ApiResponse.prompt(Syscode.ROLE_NOT_EXISTS);
        }

        if(!roleEntity.getRoleTag().equals(RoleTag.COMMONROLE)) {
            return ApiResponse.prompt(Syscode.GENERAL_ROLE_PERMIT);
        }
        UserEntity userEntity = userRepo.findOne(uid);
        userRepo.save(userDto.updateUser(userEntity,roleEntity));
        return ApiResponse.prompt(Syscode.SC_OK);
    }

    /**
     * 更新个人中心
     * @return
     */
    public ApiResponse updatePersonCenter(UpdatePersonCenterDto personCenterDto) {
        String userId = permissionSecurityUserService.getSubjectFromAccessToken();
        UserEntity userEntity =userRepo.findOne(userId);
        if(userEntity == null) {
            return ApiResponse.prompt(Syscode.ACCOUNT_NOT_EXISTS);
        }
        userEntity = personCenterDto.updateData(userEntity);
        userRepo.save(userEntity);
        SessionUser sessionUser = objectRedis.get(userId, SessionUser.class);
        if(sessionUser != null) {
            sessionUser.setHeadImg(personCenterDto.getHeadImg());
            sessionUser.setEmail(personCenterDto.getEmail());
            sessionUser.setPhone(personCenterDto.getPhone());
            String userinfo = JSON.toJSONString(sessionUser);
            redisTemplate.opsForValue().set(userEntity.getId(), userinfo, JwtConstant.JWT_REFRESH_TTL, TimeUnit.MILLISECONDS);
        }
        return ApiResponse.ok();
    }


    public Criteria<UserEntity> findUserByContions(UserSearchDto userSearchDto){
        Criteria<UserEntity> c = new Criteria<UserEntity>();
        Field[] fields = userSearchDto.getClass().getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            String fieldName = field.getName();
            Object value = BeanUtils.getBeanAttrParam(userSearchDto,fieldName);
            if (value==null) continue;
            if (fieldName.compareTo("roleName") == 0){
                c.add(Restrictions.eq("RoleEntity",RoleEntity.class,"roleName",value));
                continue;
            }
            if (fieldName.compareTo("userType") == 0){
                c.add(Restrictions.eq("userType", UserTypeEnmu.valueOf(value.toString())));
                continue;
            }
            c.add(Restrictions.like(fieldName, value.toString()));
        }
        return c;
    }

    public Page<UserListVo> searchUsers(UserSearchDto userSearchDto, Pageable pageable){
        String id = permissionSecurityUserService.getSubjectFromAccessToken();
        UserEntity curEntity = userRepo.findOne(id);
        Criteria<UserEntity> userByContions = findUserByContions(userSearchDto);
        Page<UserEntity> all = userRepo.findAll(userByContions, pageable);
        List<UserEntity> contents = all.getContent();
        List<UserListVo> userListVos = new ArrayList<UserListVo>();
        for (Iterator<UserEntity> iterator = contents.iterator(); iterator.hasNext(); ) {
            UserEntity userEntity =  iterator.next();
            if(curEntity.getRole().getRoleTag() != RoleTag.SUPPERROLE) {
                if(null != userEntity.getRole() && userEntity.getRole().getRoleTag() == RoleTag.SUPPERROLE)
                    continue;
            }
            userListVos.add(new UserListVo(userEntity));
        }
        return new PageImpl(userListVos, pageable, all.getTotalElements());
    }

    public Page<UserListVo> searchUsers(SearchUserDto searchUserDto, Pageable pageable){
        String id = permissionSecurityUserService.getSubjectFromAccessToken();
        UserEntity curEntity = userRepo.findOne(id);
        Specification<UserEntity> specification = (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            if(StringUtils.isNotEmpty(searchUserDto.getKeywords())) {
                predicates.add(cb.or(cb.like(root.get("userName"), "%"+searchUserDto.getKeywords()+"%"),
                        cb.like(root.get("realName"), "%"+searchUserDto.getKeywords()+"%"),
                        cb.like(root.get("phone"), "%"+searchUserDto.getKeywords()+"%")));
            }
            if(StringUtils.isNotEmpty(searchUserDto.getCreateTimeSlot())) {
                String[] date = searchUserDto.getCreateTimeSlot().split("~");

                LocalDate startDate = LocalDate.parse(date[0], DateTimeFormatter.ISO_LOCAL_DATE);
                LocalDate endDate = LocalDate.parse(date[1], DateTimeFormatter.ISO_LOCAL_DATE);
                long startTimestatmp = startDate.atStartOfDay().toInstant(ZoneOffset.of("+8")).getEpochSecond();
                long endTimestatmp = endDate.atStartOfDay().toInstant(ZoneOffset.of("+8")).getEpochSecond();
                predicates.add(cb.and(cb.ge(root.get("createdAt"), startTimestatmp), cb.lt(root.get("createdAt"), endTimestatmp)));
            }
            Predicate[] options = new Predicate[predicates.size()];
            return query.where(predicates.toArray(options)).getRestriction();
        };
        Page<UserEntity> all = userRepo.findAll(specification, new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), new Sort(Sort.Direction.ASC, "createdAt")));
        List<UserEntity> contents = all.getContent();
        List<UserListVo> userListVos = new ArrayList<UserListVo>();

        for (Iterator<UserEntity> iterator = contents.iterator(); iterator.hasNext(); ) {
            UserEntity userEntity =  iterator.next();
            if(curEntity.getRole().getRoleTag() != RoleTag.SUPPERROLE) {
                if(null != userEntity.getRole() && userEntity.getRole().getRoleTag() == RoleTag.SUPPERROLE)
                    continue;
            }
            userListVos.add(new UserListVo(userEntity));
        }
        return new PageImpl(userListVos, pageable, all.getTotalElements());
    }

    public SessionUser getSessionUser(String uid){
        String userinfo =  redisTemplate.opsForValue().get(uid);
        return StringUtils.isNotBlank(userinfo) ? JSON.parseObject(userinfo,SessionUser.class) : null;
    }

    /**
     * 获取系统所有权限缓存
     * @return
     */
    public List<SessionMenu> getAllSessionMenus(){
        String all_menus = redisTemplate.opsForValue().get("ALL_MENUS");
        final List<SessionMenu> sessionMenus = new ArrayList<>();
        if (StringUtils.isBlank(all_menus)){
            List<MenuEntity> menuEntities = menuRepo.findAll();
            menuEntities.forEach(menuEntity -> {
                sessionMenus.add(menuEntity.createSessionMenu());
            });
            redisTemplate.opsForValue().set("ALL_MENUS", JSON.toJSONString(sessionMenus));
        }else{
            List<SessionMenu> sessionMenuList = JSON.parseArray(all_menus, SessionMenu.class);
            sessionMenus.addAll(sessionMenuList);
        }
        return sessionMenus;
    }

    /**
     * 获取系统中所有权限实体
     * 第一次调用的时候缓存所有的权限实体
     * @return
     */
    public List<MenuEntity> getAllMenusEntity(){
        String all_menus = redisTemplate.opsForValue().get("ALL_MENUS_ENTITIES");
        final List<MenuEntity> menuEntityList = new ArrayList<>();
        if (StringUtils.isBlank(all_menus)){
            List<MenuEntity> menuEntities = menuRepo.findAll();
            menuEntities.forEach(menuEntity -> {
                menuEntityList.add(menuEntity);
            });
            redisTemplate.opsForValue().set("ALL_MENUS_ENTITIES", JSON.toJSONString(menuEntityList));
        }else{
            List<MenuEntity> menuEntities = JSON.parseArray(all_menus, MenuEntity.class);
            menuEntityList.addAll(menuEntities);
        }
        return menuEntityList;
    }


    /**
     * 获取某个角色下的所有用户id
     * @param roleId
     * @return
     */
    public List<String> getUserIds(String roleId){
        return userRepo.findUserIdListBySql(roleId);
    }


    /**
     * 密码修改
     * @param oldPass
     * @param newPass
     * @return
     */
    public ApiResponse modifyPassword(String oldPass,String newPass){
        String uid = permissionSecurityUserService.getSubjectFromAccessToken();
        if(uid == null){
            return ApiResponse.prompt(Syscode.ACCOUNT_NOT_LOGINED);
        }
        if(oldPass == null || newPass == null){
            return ApiResponse.prompt(Syscode.PASSWORD_NOT_NULL);
        }
        UserEntity userEntity =userRepo.findOne(uid);
        if(null == userEntity) {
            return ApiResponse.prompt(Syscode.ACCOUNT_NOT_EXISTS);
        }
        if (!userEntity.isAuthentication(oldPass)){//密码输入有误
            return ApiResponse.prompt(Syscode.OLD_PWD_ERROR);
        }
        userEntity.modifyPassword(newPass);

        if (userRepo.save(userEntity)==null){
            return ApiResponse.prompt(Syscode.PASSWORD_MODIFY_FAIL);
        }
        return ApiResponse.prompt(Syscode.SC_OK);
    }

    /**
     * 密码找回发送邮件
     * @param email
     * @return
     */
    public ApiResponse forgetPassword(String url, String name, String email){
        if(email == null){
            return ApiResponse.prompt(Syscode.MAIL_EMPTY);
        }
        UserEntity userEntity = userRepo.findByUserName(name);
        if(userEntity == null){
            return ApiResponse.prompt(Syscode.ACCOUNT_NOT_EXISTS);
        }
        if(StringUtils.isEmpty(userEntity.getEmail())) {
            return ApiResponse.prompt(Syscode.USER_EMAIL_NOT_SETTING);
        }
        if(!userEntity.getEmail().equals(email)) {
            return ApiResponse.prompt(Syscode.USER_EMAIL_INCORRECT);
        }
        String token = UUID.randomUUID().toString().replaceAll("-","");
        objectRedis.add("forget_password/"+token,120L,email);//有效120分钟
        //发送邮件
        try {
            gmailSender.sendSimpleMail(email,"密码找回",url+token);
        } catch (MessagingException e) {
            LOG.error(this,"邮件发送失败",e);
        }
        return ApiResponse.prompt(Syscode.SC_OK);
    }

    /**
     * 密码找回
     * @param token
     * @param username
     * @param newPass
     * @return
     */
    public ApiResponse validForgetPasswordToken(String token, String username, String newPass){
        UserEntity userEntity = userRepo.findByUserName(username);
        if(null == userEntity) {
            return ApiResponse.prompt(Syscode.ACCOUNT_NOT_EXISTS);
        }
        if(newPass == null){
            return ApiResponse.prompt(Syscode.PASSWORD_NOT_NULL);
        }
        if(StringUtils.isEmpty(userEntity.getEmail())) {
            return ApiResponse.prompt(Syscode.USER_EMAIL_NOT_SETTING);
        }
        String email = objectRedis.get("forget_password/"+token,String.class);
        if(email == null || !email.equals(userEntity.getEmail())){
            return ApiResponse.prompt(Syscode.FORGET_PASSWORD_TOKEN_NOT_EXISTS);
        }
        userEntity.modifyPassword(newPass);
        if (userRepo.save(userEntity)==null){
            return ApiResponse.prompt(Syscode.SYSTEM_EXCEPTION);
        }
        objectRedis.delete("forget_password/"+token);
        return ApiResponse.prompt(Syscode.SC_OK);
    }


    /**
     * 启用和禁用用户
     * @param uid
     * @param status
     * @return
     */
    public ApiResponse changeUserStatus(String uid,UserStatus status){
        UserEntity userEntity = userRepo.findOne(uid);
        String currUid = permissionSecurityUserService.getSubjectFromAccessToken();
        UserEntity currUserEntity =  userRepo.findOne(currUid);
        if (!currUserEntity.getRole().getRoleTag().equals(RoleTag.SUPPERROLE)) {
            return ApiResponse.prompt(Syscode.NO_PERMISSION);
        }
        if(userEntity == null){
            return ApiResponse.prompt(Syscode.ACCOUNT_NOT_EXISTS);
        }
        userEntity.setLoginFailCounter(0);
        userEntity.setUserStatus(status);
        if (userRepo.save(userEntity)==null){
            return ApiResponse.prompt(Syscode.SYSTEM_EXCEPTION);
        }
        return ApiResponse.prompt(Syscode.SC_OK);
    }


    /**
     * 不用使用，用于内部恢复账号
     * @param userName
     * @return
     */
    public ApiResponse recoverAccount(String userName){
        UserEntity userEntity = userRepo.findByUserName(userName);
        if (userEntity == null){
            return ApiResponse.ok(Syscode.ACCOUNT_NOT_EXISTS);
        }
        userEntity.setLoginFailCounter(0);
        userEntity.setUserStatus(UserStatus.NORMAL);
        userRepo.save(userEntity);
        return ApiResponse.prompt(Syscode.SC_OK);
    }

}
